package com.enba.rbacadmin.module.auth.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.enba.boot.core.base.Result;
import com.enba.rbacadmin.annotation.DistributedLock;
import com.enba.rbacadmin.module.auth.controller.req.RoleAddUpdateReq;
import com.enba.rbacadmin.module.auth.controller.req.RolePageReq;
import com.enba.rbacadmin.module.auth.controller.req.SaveRolePermissionReq;
import com.enba.rbacadmin.module.auth.controller.resp.GetUserRoleIdSetResp;
import com.enba.rbacadmin.module.auth.entity.Role;
import com.enba.rbacadmin.module.auth.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 角色表
 *
 * @author 恩爸编程
 * @since 2025-02-28
 */
@RestController
@RequestMapping("/auth/role")
@Api(tags = "角色表接口")
public class RoleController {

  @Resource private IRoleService roleService;

  /**
   * 查询所有接口
   *
   * @return list
   */
  @GetMapping
  public Result<List<Role>> findAll() {
    return Result.success(roleService.list());
  }

  /**
   * 根据id查询数据接口
   *
   * @param id id
   * @return result
   */
  @GetMapping("/{id}")
  public Result<Role> findOne(@PathVariable Integer id) {
    return Result.success(roleService.getById(id));
  }

  /**
   * 分页查询接口
   *
   * @param req
   * @return
   */
  @PostMapping("/page")
  public Result<List<Role>> findPage(@RequestBody @Validated RolePageReq req) {
    LambdaQueryWrapper<Role> roleLambdaQueryWrapper =
        Wrappers.<Role>lambdaQuery().orderByDesc(Role::getCreateTime);
    // 状态
    roleLambdaQueryWrapper.eq(Objects.nonNull(req.getStatus()), Role::getStatus, req.getStatus());
    // 角色名称
    roleLambdaQueryWrapper.eq(
        StringUtils.isNotBlank(req.getRoleName()), Role::getRoleName, req.getRoleName());

    // 创建时间开始
    roleLambdaQueryWrapper.ge(
        Objects.nonNull(req.getCreateTimeStart()), Role::getCreateTime, req.getCreateTimeStart());
    // 创建时间结束
    roleLambdaQueryWrapper.le(
        Objects.nonNull(req.getCreateTimeEnd()), Role::getCreateTime, req.getCreateTimeEnd());

    Page<Role> page =
        roleService.page(new Page<>(req.getPageNum(), req.getPageSize()), roleLambdaQueryWrapper);

    return Result.pageSuccess(page.getRecords(), page.getTotal());
  }

  @ApiOperation(value = "用户管理-分配角色（反显用户关联角色信息）")
  @PostMapping("/user-roles/{userId}")
  @DistributedLock
  public Result<List<GetUserRoleIdSetResp>> getUserRoleIdSet(
      @PathVariable Long userId, @RequestBody @Validated RolePageReq req) {
    // 获取用户角色
    Set<Long> userRoleIdSet = roleService.getUserRoleIdSet(userId);

    LambdaQueryWrapper<Role> roleLambdaQueryWrapper =
        Wrappers.<Role>lambdaQuery().orderByDesc(Role::getCreateTime);
    Page<Role> page =
        roleService.page(new Page<>(req.getPageNum(), req.getPageSize()), roleLambdaQueryWrapper);

    //    GetUserRoleIdSetResp
    List<GetUserRoleIdSetResp> pageList =
        BeanUtil.copyToList(page.getRecords(), GetUserRoleIdSetResp.class);

    // 设置选中状态
    pageList.forEach(
        item -> {
          if (userRoleIdSet.contains(item.getId())) {
            item.setLayChecked(true);
          }
        });

    return Result.pageSuccess(pageList, page.getTotal());
  }

  /**
   * 新增和更新接口
   *
   * @param req role
   * @return result
   */
  @DistributedLock
  @PostMapping
  public Result<Boolean> saveOrUpdate(@RequestBody @Validated RoleAddUpdateReq req) {
    return Result.success(roleService.saveOrUpdate(req));
  }

  /**
   * 删除接口
   *
   * @param id id
   * @return result
   */
  @DeleteMapping("/{id}")
  public Result<Boolean> delete(@PathVariable Integer id) {
    return Result.success(roleService.delete(id));
  }

  /**
   * 批量删除接口
   *
   * @param ids ids
   * @return result
   */
  @PostMapping("/del/batch")
  public Result<Boolean> deleteBatch(@RequestBody List<Integer> ids) {
    return Result.success(roleService.deleteBatch(ids));
  }

  // 角色分配权限
  @DistributedLock
  @PostMapping("/bindPerms")
  public Result<Boolean> saveRolePermission(@RequestBody @Validated SaveRolePermissionReq req) {
    return Result.success(roleService.saveRolePermission(req));
  }
}
